from osv import fields, osv
from tools.translate import _

#Add a type in partner address object named "Location"
class res_partner_address(osv.osv):
    _description ='Partner Addresses'
    _name = 'res.partner.address'
    _inherit='res.partner.address'
    _columns={
             'type': fields.selection( [('default','Default'),('location','Location'),('invoice','Invoice'), ('delivery','Delivery'), ('contact','Contact'), ('other','Other') ],'Address Type'),
             }
    
    def name_get(self, cr, user, ids, context={}):
        if not len(ids):
            return []
        res = []
        for r in self.read(cr, user, ids, ['zip','city','partner_id', 'street']):
            if context.get('contact_display', 'contact')=='partner':
                res.append((r['id'], r['partner_id'][1]))
            else:
                addr = ''
                r_zip = ''
                if r['zip']:
                    r_zip = ", " + r['zip']
                r_city=''
                if r['city']:
                    r_city = ", " + r['city']
                addr += (r['street'] or '') +  (r_zip or '') + (r_city or '')
                res.append((r['id'], addr.strip() or '/'))
        return res
res_partner_address()

class res_partner(osv.osv):
    _description ='Partner'
    _name = 'res.partner'
    _inherit='res.partner'
    
    def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=80):
        if not args:
            args=[]
        if not context:
            context={}
        ids = self.search(cr, user, [('ref','=',name)]+ args, limit=limit, context=context)
        if not len(ids):
            ids = self.search(cr, user, [('ref','ilike',name)]+ args, limit=limit, context=context)
        if not len(ids):
            ids = self.search(cr, user, [('trade_name','ilike',name)]+ args, limit=limit, context=context)            
        if not len(ids):
            ids += self.search(cr, user, [('name','=',name)]+ args, limit=limit, context=context)
        if not len(ids):
            ids += self.search(cr, user, [('name','ilike',name)]+ args, limit=limit, context=context)
        return self.name_get(cr, user, ids, context=context)

    def _newcode_suggest(self,cr,uid,context={}):
        selection=[]
#New code HCM
        cr.execute("Select newcode from vwnewcode_partner")
        for x in cr.fetchall():            
            selection.append((x[0],x[0]))
        return selection
    
    def _onchange_suggest_code(self, cr, uid, ids,new_code):
        if new_code:
            val={'value':{'ref':new_code,'newcode_suggest':False}}
        else:
            val={}
        return val
    
    
    def _parter_address_fnc(self, cr, uid, ids, name, arg, context=None):
        res={}
        if ids:
            tmp_list=[]
            partner_ids_lst=",".join(map(str,ids))
            
            cr.execute("Select rp.id,street || case when coalesce(city,'0')='0' then '' else ', ' || city end as address\
                         from res_partner rp left join res_partner_address on rp.id = partner_id\
                         where rp.id in (%s)" % (partner_ids_lst)) #coalesce(partner_id,0)>0 and partner_
            for id,addr in cr.fetchall():
                if id not in tmp_list:
                    res[id] =addr
                    tmp_list.append(id)            
        return res
    
    def _parter_tel(self, cr, uid, ids, name, arg, context=None):
        res={}
        if ids:
            tmp_list=[]
            partner_ids=",".join(map(str,ids))
            cr.execute("Select rp.id,phone\
                         from res_partner rp left join res_partner_address on rp.id = partner_id\
                         where rp.id in (%s)" % (partner_ids))
            for id,addr in cr.fetchall():
                if id not in tmp_list:
                    res[id] =addr
                    tmp_list.append(id)            
        return res
    
    def _parter_fax(self, cr, uid, ids, name, arg, context=None):
        res={}
        if ids:
            tmp_list=[]
            partner_ids=",".join(map(str,ids))
            cr.execute("Select rp.id,fax\
                         from res_partner rp left join res_partner_address on rp.id = partner_id\
                         where rp.id in (%s)" % (partner_ids))
            for id,addr in cr.fetchall():
                if id not in tmp_list:
                    res[id] =addr
                    tmp_list.append(id)            
        return res
    
    _columns={
             'address_default':fields.function(_parter_address_fnc,type='char',string="Address",size=254,method=True),
             'tel_default':fields.function(_parter_tel,type='char',string="Phone",size=20,method=True),
             'fax_default':fields.function(_parter_fax,type='char',string="Fax",size=20,method=True),

             'ref':fields.char('Code', size=64,required=True),
             'trade_name':fields.char('Trade Name',size=25),
             'vat_code':fields.char('V.A.T. Code',size=20),
             'newcode_suggest':fields.selection(_newcode_suggest,'New Code',size=16,store=False),#,readonly=True,states={'draft':[('readonly',False)]}
             }
    _defaults={
               'customer': lambda *a: False,
               'supplier': lambda *a: 1,
               }
    _sql_constraints = [
        ('code_uniq', 'unique (ref)', 'The Code of the Partner must be unique !')
    ]
    def _new_type_def(self, cr, uid, context):
        typeoforder = False
        if context:
            if 'typeoforder' in context:
                typeoforder = context['typeoforder']
        return typeoforder
res_partner()
